﻿using System;
using System.Collections.Generic;
using System.IO;
using RayDen.RayEngine.Core.Types;

namespace RayDen.RayEngine.Core.Components
{
    public class SceneCache
    {

        public string FrameName { get; set; }
        public DateTime CreationDate { get; set; }

        public SceneCache()
        {
            CreationDate = DateTime.UtcNow;
        }


        public GpuSmitsBVHNode[] BvhData;

        public void Save(string path)
        {
            Console.WriteLine("Saving bvh cache {0}" , path);
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                foreach (var gpuSmitsBvhNode in BvhData)
                {
                    fs.Write(gpuSmitsBvhNode.GetData(), 0, 32);
                }
            }
        }


        public static SceneCache Load(string path)
        {
            Console.WriteLine("Loading bvh cache {0}" ,path);

            var res = new SceneCache();
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var nodes = new List<GpuSmitsBVHNode>(1000);
                var buffer = new byte[GpuSmitsBVHNode.NodeSize];
                bool done = false;
                while (!done)
                {
                    if (fs.Read(buffer, 0, 32) < 32)
                    {
                        done = true;
                    }
                    else
                    {
                        nodes.Add(new GpuSmitsBVHNode(buffer));
                    }
                }
                res.BvhData = nodes.ToArray();

            }

            return res;
        }
    }
}
